import { ArticleDetail, ArticleComment } from "@/types/data"
import { ArticleAction, ResetAction } from "@/types/store"

type ArticleState = {
  // 文章详情
  detail: ArticleDetail
  comment: ArticleComment
}

const initialState = {
  detail: {},
  comment: {
    // 注意：此处为 results 属性设置默认值为数组。这样，不管有没有评论数据，results 都是一个数组
    results: [] as ArticleComment["results"],
  },
} as ArticleState

const article = (state = initialState, action: ArticleAction | ResetAction): ArticleState => {
  if (action.type === "article/get") {
    return {
      ...state,
      detail: action.payload,
    }
  }
  if (action.type === "article/updateInfo") {
    return {
      ...state,
      detail: {
        ...state.detail,
        [action.payload.name]: action.payload.value,
      },
    }
  }
  if (action.type === "article/getArticleComments") {
    const { total_count, end_id, last_id, results, actionType } = action.payload
    return {
      ...state,
      comment: {
        total_count,
        end_id,
        last_id,
        results: actionType === "append" ? [...state.comment.results, ...results] : [...results],
      },
    }
  }
  if (action.type === "article/addComment") {
    return {
      ...state,
      comment: {
        ...state.comment,
        total_count: state.comment.total_count + 1,
        results: [action.payload, ...state.comment.results],
      },
    }
  }
  if (action.type === "reset" && action.payload === "article") {
    return initialState
  }
  return state
}

export default article
